import {setStore, getStore} from '@/utils/store';
import store from '../index'
import {IMScoketJS} from "@/im/ImSocketJs";
import {myFriend, records, getUserInfo} from "@/api/base/chat";
import { ElMessage, ElMessageBox } from 'element-plus'

let Variable = {
    // 消息窗
    messageBox: null
}

function unsubscribeList(subscribeList) {
    if (subscribeList && subscribeList.length) {
        for (let subscribe of subscribeList) {
            subscribe.unsubscribe();
        }
    }
}

let im = {
    state: {
        // 当前用户
        user: getStore({name: 'userInfo'}),
        // 会话列表
        sessions: [],
        // 消息列表
        messages: [],
        // 当前会话
        currentSession: null,
        // 过滤出只包含这个key的会话
        filterKey: '',
        visible: false,
        imSocketJs: null,
        imUnreadList: [], // 未读列表
        unconnect: true, // 未链接
        subscribeList: [], // 订阅
    },
    actions: {
        imConnect: ({commit}) => commit("IM_CONNECT"),
        /**
         * 发起聊天
         * @param commit
         * @returns {*}
         */
        launchChat: ({commit}, value) => {
            let userId = value.userId, fromUserId = value.fromUserId;
            return new Promise((resolve, reject) => {
                getUserInfo(userId).then(res => {
                    if (res && res.data.success) {
                        commit("LAUNCH_CHAT", {data: res.data.data, fromUserId: fromUserId});
                        resolve()
                    } else {
                        ElMessage({
                            message: res.data.message,
                            type: 'error'
                        });
                        reject(new Error(res.data.message))
                    }
                }, error => {
                    reject(error)
                })
            })
        },
        sendMessage: ({commit}, value) => commit('SEND_MESSAGE', value),
        pushRecord: ({commit}, record) => commit('PUSH_RECORD', record),
        // selectSession: ({commit}, userId) => commit('SELECT_SESSION', userId),
        search: ({commit}, value) => commit('SET_FILTER_KEY', value),
        visible: ({commit}, value) => commit("SET_IM_VISIBLE", value),
        imRead:({commit}, value) => commit("IM_READ",value),
        clearCurrentSession: ({commit}) => commit("CLEAR_CURRENT_SESSION"),
        /**
         * 关闭连接
         * @param commit
         * @returns {*}
         */
        closeConnect: ({commit}) => commit("CLOSE_CONNECT"),
    },
    mutations: {
        SET_IM_USER_INFO(state, data) {
            state.user = data
        },
        /**
         * 发起连接
         * @param state
         * @constructor
         */
        IM_CONNECT(state) {
            state.sessions = [];
            state.messages = [];
            state.imUnreadList = [];
            state.unconnect = true;
            state.user = getStore({name: 'userInfo'});
            console.log("state.user",state.user);
            if (!state.currentSession) {
                state.currentSession = {};
            }
            unsubscribeList(state.subscribeList);
            state.imSocketJs = new IMScoketJS({
                // ws: "http://10.78.105.113:81/ws",
                ws: "/ws",
                onConnectedListener: (stompClient, headers) => {
                    if (Variable.messageBox) {
                        Variable.messageBox.close();
                    }
                    state.unconnect = false;
                    // 获取会话列表
                    myFriend().then((res) => {
                        if (res.data && res.data.success) {
                            let data = res.data.data;
                            state.sessions.push(...(data || []));
                            state.sessions.forEach(item=> {
                                // if (state.currentSession) {
                                //     console.log("~~~~~~~~~~~~~~~~~~~~~~~")
                                //     return (state.currentSession || state.currentSession.fromUserId !== item.fromUserId) && item.unreadCount > 0;
                                // }
                                if (item.unreadCount > 0) {
                                    for (let i = 0; i<item.unreadCount; i++) {
                                        state.imUnreadList.push({
                                            fromUserId: item.fromUserId,
                                            descName: "【"+item.fromUserId+"】发来一条新消息",
                                        })
                                    }
                                }
                            });
                        } else {
                            ElMessage({
                                message: res.data.message || "加载失败",
                                type: 'error'
                            });
                        }
                    }, (err) => {
                        ElMessage({
                            message: "IM信息获取失败，请刷新重试！",
                            type: 'error'
                        });
                    }).then(() => {
                        //通知 /topic/public
                        // 订阅消息
                        const chatSingleSubscribe = stompClient.subscribe('/chat/single/' + state.user.user_id, (payload) => {
                            let message = JSON.parse(payload.body);
                            // if (!state.currentSession || (state.currentSession && state.currentSession.fromUserId !== message.fromUserId)) {
                            //  if (!state.currentSession || (state.currentSession && state.currentSession.fromUserId !== message.fromUserId)) {
                            // 非当前会话的消息
                            console.log("收到消息：",message);
                            if (message.from === 1000) {
                                console.log("321321321321321")
                                state.imUnreadList.push({
                                    fromUserId: message.from,
                                    descName: "您有一条新的【系统通知】",
                                })
                            } else {
                                state.imUnreadList.push({
                                    fromUserId: message.from,
                                    descName: "【" + message.fromName + "】发来一条新消息",
                                })
                            }
                            return;
                            // }
                            if (!state.currentSession || JSON.stringify(state.currentSession) === "{}") {
                                return;
                            }
                            store.commit('PUSH_RECORD', {
                                id: message.id,
                                content: message.content,
                                date: new Date(),
                                type: message.type,
                                // fromUserId: message.fromUserId,
                                from: message.from,
                                formName: message.fromName,
                                formAvatar: message.fromAvatar,
                                to: message.to,
                                toName: message.toName,
                                toAvatar: message.toAvatar,
                            })
                        });
                        // 用户上线
                        state.imSocketJs.send("/blade-guoren/im/chat.addUser", {
                            from: state.user.user_id,
                            type: 'JOIN'
                        });

                        state.subscribeList.push(chatSingleSubscribe)
                    });
                },
                onConnectErrorListener: (err)=> {
                    state.unconnect = true;
                },
                onReConnectListener: (isReconnect, count, totalCount, reconnectTime) => {
                    if (isReconnect) {
                        Variable.messageBox = ElMessage({
                            message: `正在尝试重新连接IM，请稍后...(${count}/${totalCount})`,
                            type: 'error',
                            duration: reconnectTime,
                            onClose: ()=> {
                                Variable.messageBox = null;
                            }
                        });
                    } else {
                        ElMessageBox({
                            title: `IM连接错误`,
                            message: "请稍后手动刷新页面尝试！",
                            type: 'error',
                            duration: reconnectTime,
                        });
                    }
                }
            });
            state.imSocketJs.initWebSocket();
        },
        LAUNCH_CHAT(state, value) {
            const data = value.data;
            const user = {user_id: data.id, name: data.name, avatar: data.avatar};
            // let findUser = state.sessions.find((item)=> item.user_id === user.user_id);
            // if (findUser) {
            //   Object.assign(findUser, user);
            // } else {
            //   state.sessions.unshift(user);
            //
            // }
            state.currentSession = {
                user: user,
                fromUserId: value.fromUserId,
                messages: [],
            };
            state.visible = true;
        },
        /**
         * 发送聊天消息
         * @param sessions
         * @param currentSession
         * @param user
         * @param imSocketJs
         * @param content
         * @constructor
         */
        SEND_MESSAGE({sessions, currentSession, user, imSocketJs, unconnect}, value) {
            console.log("user",user);
            console.log("SEND_MESSAGE",imSocketJs);
            if (unconnect) {
                ElMessage({
                    message: "IM未连接或连接失败，请刷新重试！",
                    type: 'error'
                });
                return;
            }
            // if (value.type === "CHAT") {
            //     currentSession.messages.push({
            //         content: value.content,
            //         date: new Date(),
            //         self: true,
            //         type: value.type,
            //         fromUserId: user.user_id,
            //         from: user.user_id,
            //         formUser: {user_id: user.user_id, name: user.nick_name, avatar: user.avatar},
            //         to: value.toUser.id,
            //         toUser: {user_id: value.toUser.user_id, name: value.toUser.name, avatar: value.toUser.avatar}
            //     });
            // }
            if (imSocketJs) {
                // 发送消息
                console.log("%%%%%%开始发送%%%%%%%%%%");
                imSocketJs.send("/blade-anwise/im/chat.sendMessage", {
                    from: user.user_id,
                    content: value.content,
                    // fromUserId: currentSession.fromUserId,
                    type: value.type,
                    to: value.toUser.id,
                })
            }
        },
        SAVE_SELF_MESSAGE({sessions, currentSession, user, unconnect}, value) {
            if (unconnect) {
                ElMessage({
                    message: "IM未连接或连接失败，请刷新重试！",
                    type: 'error'
                });
                return;
            }
            const data = {
                content: value.content,
                date: new Date(),
                self: true,
                type: value.type,
                flag: 1,
                file: value.file || {},
                fromUserId: currentSession.fromUserId,
                from: user.user_id,
                formUser: {user_id: user.user_id, name: user.nick_name, avatar: user.avatar},
                to: currentSession.user.user_id,
                toUser: {user_id: currentSession.user.user_id, name: currentSession.user.name, avatar: currentSession.user.avatar}
            };
            currentSession.messages.push(data);
        },
        /**
         * 选择会话
         * @param state
         * @param userId
         * @constructor
         */
        SELECT_SESSION(state, userId) {
            // state.currentSessionId = id;
            if (state.currentSession && state.currentSession.user && state.currentSession.user.user_id === userId) {
                return;
            }
            state.currentSession = {
                user: state.sessions.find(item => item.user_id === userId),
                messages: [],
            };
        },
        /**
         * 接收消息 封装
         * @param state
         * @param record
         * @constructor
         */
        PUSH_RECORD(state, record = {}) {
            if (record.type === "PUBLIC") {
                if (state.user.user_id !== record.to) {
                    return;
                }
            }
            let message = {
                id: record.id,
                content: record.content,
                date: record.date,
                type: record.type,
                self: state.user.user_id === record.from,
                // fromUserId: record.fromUserId,
                from: record.from,
                to: record.to,
                formUser: {user_id: record.form, name: record.formName, avatar: record.formAvatar},
                toUser: {user_id: record.to, name: record.toName, avatar: record.toAvatar}
            };
            if (!state.currentSession.messages) {
                state.currentSession.messages = []
            }
            if (record.old) {
                state.currentSession.messages.unshift(message);
            } else {
                state.currentSession.messages.push(message);
            }
        },
        /**
         * 搜索
         * @param state
         * @param value
         * @constructor
         */
        SET_FILTER_KEY(state, value) {
            state.filterKey = value;
        },
        /**
         * 设置IM聊天窗口的显示隐藏
         * @param state
         * @param value  true/false
         * @constructor
         */
        SET_IM_VISIBLE(state, value) {
            state.visible = value
        },
        /**
         * 关闭连接
         * @param state
         * @constructor
         */
        CLOSE_CONNECT(state) {
            if (state.imSocketJs) {
                unsubscribeList(state.subscribeList);
                state.imSocketJs.disconnect();
                state.sessions = [];
                state.messages = [];
                state.currentSession = {};
                state.filterKey = "";
                state.visible = "";
                state.imSocketJs = null;
                state.unconnect = true;
            }
        },
        CLEAR_CURRENT_SESSION(state) {
            state.currentSession = {};
        },
        /**
         * 设置已读
         * @param state
         * @constructor
         */
        IM_READ(state, value) {
            // state.imUnreadList.filter(item=> {
            //   if (state.currentSession) {
            //     return state.currentSession.fromUserId !== item.fromUserId;
            //   }
            //   return true;
            // })
            for (let index in state.imUnreadList) {
                let item = state.imUnreadList[index];
                if (value.fromUserId == item.fromUserId) {
                    state.imUnreadList.splice(index, 1)
                    return;
                }
            }
        }
    }
};

// store.watch(
//   (state) => state.sessions,
//   (val) => {
//     console.log('CHANGE: ', val);
//     localStorage.setItem('vue-chat-session', JSON.stringify(val));
//   },
//   {
//     deep: true
//   }
// );

export default im;
